package com.ywgt.system.auth;


import com.ywgt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token验证
 */
public class TokenAuthFilter extends OncePerRequestFilter {

    @Qualifier("userDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //拿到请求头中的token
        String token = request.getHeader("Authorization");
        String username=null;
        if (!StringUtils.isEmpty(token)){
            try {
                //根据token拿到用户名
                username = JWTUtil.parseJwtClaims(token);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
             //判断是否存在用户并且现在是否有用户登录
            if (null!=username&& null==SecurityContextHolder.getContext().getAuthentication()) {
                //登录，返回用户
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (JWTUtil.volidateToken(token,userDetails)){
                    //将用户重新放到Context中
                    UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(
                            userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //放行
        filterChain.doFilter(request,response);
    }
}
